package com.nblog.controller.admin;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StrKit;
import com.nblog.annotation.ControllerBind;
import com.nblog.constant.ApiConstant;
import com.nblog.constant.Constant;
import com.nblog.model.SysUser;
import com.nblog.plugin.ioc.annotation.JFAutowired;
import com.nblog.resp.ApiResp;
import com.nblog.service.SysLoginRecordService;
import com.nblog.service.SysUserService;
import com.nblog.utils.encrypt.Md5Utils;
@ControllerBind(controllerKey="/admin/login")
public class LoginController extends Controller {
	@JFAutowired
	SysUserService sysUserService;
	@JFAutowired
	SysLoginRecordService sysLoginRecordService;
	public void index(){
		String url=getPara("url", "/admin/index");
		setAttr("url", url);
		render("index.html");
	}
	//验证码
	public void captcha(){
		renderCaptcha();
	}
	@Before(POST.class)
	public void ajaxlogin(){
		String username=getPara("username");
		String password=getPara("password");
		boolean captchaCode=validateCaptcha("captchaCode");
		ApiResp apiResp=new ApiResp();
		if(StrKit.isBlank(username)){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("请输入用户名");
			renderJson(apiResp);
			return;
		}
		if(StrKit.isBlank(password)){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("请输入密码");
			renderJson(apiResp);
			return;
		}
		if(!captchaCode){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("验证码错误");
			renderJson(apiResp);
			return;
		}
		password=new Md5Utils().getMD5(password);
		SysUser sysUser=SysUser.dao.findFirst("select * from sys_user where name=?", username);
		if(sysUser==null){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("用户不存在");
			renderJson(apiResp);
			return;
		}
		if(sysLoginRecordService.hasOverLoginErrTimes(sysUser.getId())){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("今天连续输入密码错误次数超过5次");
			renderJson(apiResp);
			return;
		}
		if(!sysUser.getPwd().equals(password)){
			sysLoginRecordService.saveSysLoginRecord(sysUser.getId(),0);
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("密码错误");
			renderJson(apiResp);
			return;
		}
		if(sysUser.getStatus()==0){
			apiResp.setCode(ApiConstant.CODE_FAIL);
			apiResp.setMsg("用户被冻结，请联系管理员");
			renderJson(apiResp);
			return;
		}
		sysLoginRecordService.saveSysLoginRecord(sysUser.getId(),1);
		setSessionAttr(Constant.SYSUSER, sysUser);
		apiResp.setCode(ApiConstant.CODE_SUCCESS);
		apiResp.setMsg("登录成功");
		renderJson(apiResp);
	}
	
	public void logout(){
		removeSessionAttr(Constant.SYSUSER);
		redirect("/admin/login");
	}
}
